<?php

/**
 * 夏日葵电商系统
 * http://www.xiarikui.com
 */

namespace Admin\Controller;

use Think\AjaxPage;
use Think\Page;
use Admin\Model\UserModel;

class UserController extends BaseController {

    public function index() {
        $this->display();
    }

    /**
     * 更改级别
     */
    public function test() {
        $userInfo = M("UserInfo")->where('status=1')->field('user_id,apply_level')->select();
        $userLevel = M('UserLevel')->where("1=1")->getField('level_id,discount');
        foreach ($userInfo as $key => $value) {
            $data['level'] = $value['apply_level'];
            $data['is_distribut'] = 1;
            $data['discount'] = $userLevel[$value['apply_level']] / 100;
            D('Users')->where(array('user_id' => $value['user_id']))->save($data);
        }
        echo count($userInfo);
    }

    /**
     * 上级绑定
     */
    public function test1() {
        $user = D('users')->where('1=1 and first_leader>0')->field('user_id,first_leader,second_leader')->select();
        $orderMod = D('order');
        foreach ($user as $key => $value) {
            $order_data['first_leader'] = $value['first_leader'];
            $order_data['second_leader'] = $value['second_leader'];
            $orderMod->where(array('user_id' => $value['user_id'], 'pay_status' => 0))->save($order_data);
        }
        dump($user);
    }

    /**
     * 会员列表
     */
    public function ajaxIndex() {
        $condition = array();
        I('mobile') ? $condition['u.mobile'] = array('like', '%' . I('mobile') . '%') : false;
//        I('email') ? $condition['email'] = array('like', '%' . I('email') . '%') : false;
        I('user_id') ? $condition['u.user_id'] = I('user_id') : false;
        I('nickname') ? $condition['u.username'] = array('like', '%' . I('nickname') . '%') : false;
        $sort_order = I('order_by', 'u.user_id') . ' ' . I('sort', 'desc');

        $model = M('users')->alias('u');
        $count = $model->where($condition)->count();
        $Page = new AjaxPage($count, 10);
        foreach ($condition as $key => $val) {
            $Page->parameter[$key] = urlencode($val);
        }
        $userList = $model->alias('u')
            ->join('left join __REGION__ as r on u.province = r.id and r.level = 1')
            ->join('left join __REGION__ as r1 on u.city = r1.id and r1.level = 2')
            ->join('left join __QUESTION__ as q on u.user_id = q.user_id')
            ->field('u.*,r.name as p_name,r1.name as c_name,count(q.id) as count')
            ->group('u.user_id')
            ->where($condition)->order($sort_order)->limit($Page->firstRow . ',' . $Page->listRows)->select();

        $show = $Page->show();
        $this->assign('userList', $userList);
        $this->assign('page', $show);
        $this->display();
    }

    public function export_user()
    {

        $selected = array_filter(I('post.selected'));
        if(empty($selected)){
            return $this->error('请选择导出的条目');
        }

        $strTable = '<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">ID</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">会员昵称</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">手机号码</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">所在地区</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">开启账户</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">总提问数</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">注册日期</td>';
        $strTable .= '</tr>';

        $obj = M('users')->alias('u')
                ->join('left join __REGION__ as r on u.province = r.id and r.level = 1')
                ->join('left join __REGION__ as r1 on u.city = r1.id and r1.level = 2')
                ->join('left join __QUESTION__ as q on u.user_id = q.user_id')
                ->field('u.*,r.name as p_name,r1.name as c_name,count(q.id) as count')
                 ->group('u.user_id')
                ->where('id in ('.implode(',',$selected).')')
                 ->order('u.user_id desc')->select();

        foreach($obj as $val) {
            $strTable .= '<tr>';
            $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['user_id'] . ' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['username'] . ' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['mobile'] . ' </td>';

            $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['p_name'].'/'.$val['c_name'] . '  </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">' . (($val['is_lock'] == 0) ? '开启':'<font color="red">屏蔽</font>' ). '  </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['count'] . ' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">' . date('Y-m-d H:i:s',$val['reg_time']) . ' </td>';

            $strTable .= '</tr>';
        }
        $strTable .= '</table>';

        downloadExcel($strTable, '会员表');
        exit();
    }


    public function export_userlog()
    {

        $selected = array_filter(I('post.selected'));
        if(empty($selected)){
            return $this->error('请选择导出的条目');
        }

        $strTable = '<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">ID</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">用户名称</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">用户手机</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">操作</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">支付状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">交易单号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">商户单号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">支付时间</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">生成时间</td>';
        $strTable .= '</tr>';

        $obj =M('pay_log')->alias('ul')
            ->join('left join __USERS__ as u on ul.user_id = u.user_id ')
            ->field('ul.*,u.username,u.mobile')
            ->where('id in ('.implode(',',$selected).')')
            ->order('add_time desc')
            ->select();
        $type = C('USER_LOG_TYPE');
        foreach($obj as $val) {
            $strTable .= '<tr>';
            $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['id'] . ' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['username'] . ' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['mobile'] . ' </td>';

            $strTable .= '<td style="text-align:left;font-size:12px;">' . $type[$val['type']]. '  </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['money'] . ' </td>';

            $strTable .= '<td style="text-align:left;font-size:12px;">' . (($val['status'] == 1) ? '成功':'<font color="red">失败</font>' ). '  </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['trade_sn'] . ' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['shop_sn'] . ' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">' . date('Y-m-d H:i:s',$val['pay_time']) . ' </td>';

            $strTable .= '<td style="text-align:left;font-size:12px;">' . date('Y-m-d H:i:s',$val['add_time']) . ' </td>';

            $strTable .= '</tr>';
        }
        $strTable .= '</table>';

        downloadExcel($strTable, '会员支付记录表');
        exit();
    }

    public function getCityByAjax() {
        $pid = I('get.province_id','0');
        $city =  M('region')->where('parent_id = '.$pid.' and level = 2')->select();
        exit(json_encode(
            array('list' => $city)
        ));
    }


    /**
     * 会员详细信息查看
     */
    public function detail() {
        $uid = I('get.id');
        $user = D('users')->where(array('user_id' => $uid))->find();
        if (!$user)
            exit($this->error('会员不存在'));
        if (IS_POST) {
            $row = M('users')->where(array('user_id' => $uid))->save($_POST);
            if ($row)
                exit($this->success('修改成功' ,U('user/index')));
            exit($this->error('未作内容修改或修改失败'));
        }

        $province =  M('region')->where('level = 1')->select();
        $city =  M('region')->where('level = 2 and parent_id = '.$user['province'])->select();
        $this->assign('user', $user);
        $this->assign('provinceList', $province);
        $this->assign('cityList', $city);
        $this->initEditor('head_pic');
        $this->display();
    }

    /**
     * 添加用户
     */
    public function addUser() {
        if (IS_POST) {
            $data = I('post.');
            $user_obj = new UserModel();
            $res = $user_obj->addUser($data);
            if ($res['status'] == 1) {
                $this->success('添加成功', U('User/index'));
                exit;
            } else {
                $this->error('添加失败,' . $res['msg'], U('User/index'));
            }
        }

        $province =  M('region')->where('level = 1')->select();
        $this->assign('provinceList', $province);
        $this->initEditor('head_pic');
        $this->display('detail');
    }

    /**
     * 用户收货地址查看
     */
    public function address() {
        $uid = I('get.id');
        $lists = D('user_addr')->where(array('user_id' => $uid))->select();
        $regionList = M('Region')->getField('id,name');
        $this->assign('regionList', $regionList);
        $this->assign('lists', $lists);
        $this->display();
    }

    /**
     * 删除会员
     */
    public function delete() {
        $uid = I('get.id');
        $row = M('users')->where(array('user_id' => $uid))->delete();
        if ($row) {
            $this->success('成功删除会员');
        } else {
            $this->error('操作失败');
        }
    }

    /**
     * 账户资金记录
     */
    public function log() {
        $user_id = I('get.id') ? I('get.id') : I('post.user_id');
        $type = I('post.type');
        $username = I('post.username');
        $mobile = I('post.mobile');
        if($user_id){
            $where['u.user_id'] =  $user_id;
        }
        if($type){
            $where['type'] =  $type;
        }
        if($username){
            $where['u.username'] =  $username;
        }
        if($mobile){
            $where['u.mobile'] =  $mobile;
        }
        $where['ul.user_id'] = array('gt' , 0);
        $count = M('pay_log')->alias('ul')
            ->join('left join __USERS__ as u on ul.user_id = u.user_id ')
            ->field('ul.*,u.username,u.mobile')
            ->where($where)->count();
        $page = new Page($count);
        $lists =M('pay_log')->alias('ul')
            ->join('left join __USERS__ as u on ul.user_id = u.user_id ')
            ->field('ul.*,u.username,u.mobile')
            ->where($where)->order('add_time desc')->limit($page->firstRow . ',' . $page->listRows)->select();

        $this->assign('user_id', $user_id);
        $this->assign('post', I('post.'));
        $this->assign('page', $page->show());
        $this->assign('type', C('USER_LOG_TYPE'));
        $this->assign('lists', $lists);
        $this->display('userLog');
    }

    /**
     * 账户资金调节
     */
    public function userLogEdit() {
        $user_id = I('get.id');
        if (!$user_id > 0)
            $this->error("参数有误");
        if (IS_POST) {
            $m_op_type = I('post.money_act_type');
            $user_money = I('post.user_money');
            $user_money = $m_op_type ? $user_money : 0 - $user_money;

            $p_op_type = I('post.point_act_type');
            $pay_points = I('post.pay_points');
            $pay_points = $p_op_type ? $pay_points : 0 - $pay_points;

            $f_op_type = I('post.frozen_act_type');
            $frozen_money = I('post.frozen_money');
            $frozen_money = $f_op_type ? $frozen_money : 0 - $frozen_money;

            $desc = I('post.desc');
            if (!$desc)
                $this->error("请填写操作说明");
            if (userLog($user_id, $user_money, $pay_points, $desc)) {
                $this->success("操作成功", U("Admin/User/userLog", array('id' => $user_id)));
            } else {
                $this->error("操作失败");
            }
            exit;
        }
        $this->assign('user_id', $user_id);
        $this->display();
    }

    /**
     * 充值记录
     */
    public function recharge() {
        $timegap = I('timegap');
        $nickname = I('nickname');
        $map = array();
        if ($timegap) {
            $gap = explode(' - ', $timegap);
            $begin = $gap[0];
            $end = $gap[1];
            if ($begin == $end) {
                $map['ctime'] = array('between', array(strtotime($begin), strtotime($end . ' +1 days')));
            } else {
                $map['ctime'] = array('between', array(strtotime($begin), strtotime($end)));
            }
        }
        if ($nickname) {
            $map['nickname'] = array('like', "%$nickname%");
        }
        $count = D('recharge')->where($map)->count();
        $page = new Page($count);
        $lists = D('recharge')->where($map)->limit($page->firstRow . ',' . $page->listRows)->order('order_id desc')->select();
        $this->assign('page', $page->show());
        $this->assign('lists', $lists);
        $this->display();
    }

    /**
     * 提现列表
     */
    public function account() {
        $this->display();
    }

    /**
     *
     */
    public function ajaxCash() {
        $condition = array();
        $type = I('type', 2);
        $condition['type'] = $type;
        if (IS_POST) {
            if (I('status') != '-1') {
                $condition['status'] = I('status');
            }
            if (I('user_id')) {
                $condition['user_id'] = I('user_id');
            }
            if (I('account_bank')) {
                $condition['account_bank'] = I('account_bank');
            }
            if (I('account_name')) {
                $condition['account_name'] = I('account_name');
            }
        }

        $model = D('cash');
        $count = $model->where($condition)->count();
        $Page = new AjaxPage($count, 10);
        foreach ($condition as $key => $val) {
            $Page->parameter[$key] = urlencode($val);
        }
        $cashList = $model->where($condition)->limit($Page->firstRow . ',' . $Page->listRows)->order('id desc')->select();
        $show = $Page->show();
        $this->assign('cashList', $cashList);
        $this->assign('page', $show);
        $this->display();
    }

    /**
     * 审核提现
     */
    public function auditCash() {
        $id = I('id');
        if (empty($id)) {
            $this->error('参数错误!');
        }
        $userMod = D('Users');
        $cashMod = D('cash');
        $cash = $cashMod->where(array('id' => $id))->find();
        $user = $userMod->where(array('user_id' => $cash['user_id']))->field('user_id,user_money,nickname')->find();
        if (IS_POST) {
            $data['status'] = I('post.status');
            $data['remark'] = I('post.remark');
            $cashMod->where(array('id' => $id))->save($data);
            $user_log_data['user_id'] = $cash['user_id'];
            $user_log_data['change_time'] = time();
            if (I('post.status') == 1) {
                $user_log_data['frozen_money'] = -$cash['money'];
                $userMod->where(array('user_id' => $cash['user_id']))->setDec('frozen_money', $cash['money']);
                $user_log_data['desc'] = '平台提现余额通过';
                D('user_log')->add($user_log_data);
            } elseif (I('post.status') == 2) {
                $user_log_data['frozen_money'] = $cash['money'];
                $userMod->where(array('user_id' => $cash['user_id']))->setDec('frozen_money', $cash['money']);
                $userMod->where(array('user_id' => $cash['user_id']))->setInc('user_money', $cash['money']);
                $user_log_data['desc'] = '平台提现余额不通过';
                D('user_log')->add($user_log_data);
            }
            $this->success('操作成功!', U('Admin/AppDistribut/cash'));
            exit();
        }
        $this->assign('cash', $cash);
        $this->assign('user', $user);
        $this->display();
    }

    public function level() {
        $act = I('GET.act', 'add');
        $this->assign('act', $act);
        $level_id = I('GET.level_id');
        $level_info = array();
        if ($level_id) {
            $level_info = D('user_level')->where('level_id=' . $level_id)->find();
            $this->assign('info', $level_info);
        }
        $this->display();
    }

    public function levelList() {
        $Ad = M('user_level');
        $res = $Ad->where('1=1')->order('level_id')->page($_GET['p'] . ',10')->select();
        if ($res) {
            foreach ($res as $val) {
                $list[] = $val;
            }
        }
        $this->assign('list', $list);
        $count = $Ad->where('1=1')->count();
        $Page = new \Think\Page($count, 10);
        $show = $Page->show();
        $this->assign('page', $show);
        $this->display();
    }

    public function levelHandle() {
        $data = I('post.');
        if ($data['act'] == 'add') {
            $r = D('user_level')->add($data);
        }
        if ($data['act'] == 'edit') {
            $r = D('user_level')->where('level_id=' . $data['level_id'])->save($data);
            $user['level'] = $data['level_id'];
            $discount = D('UserLevel')->where(array('level_id' => $data['level_id']))->getField('discount');
            $level['discount'] = $discount / 100;
            M('users')->where(array('level' => $data['level_id']))->save($level);
        }

        if ($data['act'] == 'del') {
            $r = D('user_level')->where('level_id=' . $data['level_id'])->delete();
            if ($r)
                exit(json_encode(1));
        }

        if ($r) {
            $this->success("操作成功", U('Admin/User/levelList'));
        } else {
            $this->error("操作失败", U('Admin/User/levelList'));
        }
    }

    /**
     * 搜索用户名
     */
    public function searchUser() {
        $search_key = trim(I('search_key'));
        $list = M('users')->where(" mobile like '%$search_key%' ")->select();
        foreach ($list as $key => $val) {
            echo "<option value='{$val['user_id']}'>{$val['mobile']}</option>";
        }
        exit;
//        if (strstr($search_key, '@')) {
//            $list = M('users')->where(" email like '%$search_key%' ")->select();
//            foreach ($list as $key => $val) {
//                echo "<option value='{$val['user_id']}'>{$val['email']}</option>";
//            }
//        } else {
//            $list = M('users')->where(" mobile like '%$search_key%' ")->select();
//            foreach ($list as $key => $val) {
//                echo "<option value='{$val['user_id']}'>{$val['mobile']}</option>";
//            }
//        }
        exit;
    }

    /**
     * 申请列表
     */
    public function userInfo() {
        $this->display();
    }

    public function ajaxUserInfo() {
        $condition = array();
        if (IS_POST) {
            if (I('status') != 0) {
                $condition['status'] = I('status');
            }
        }
        $level = D('UserLevel')->where('level_id<5')->getField('level_id,level_name,discount');
        $model = D('UserInfo');
        $count = $model->where($condition)->count();
        $Page = new AjaxPage($count, 10);
        foreach ($condition as $key => $val) {
            $Page->parameter[$key] = urlencode($val);
        }
        $list = $model->where($condition)->limit($Page->firstRow . ',' . $Page->listRows)->order('id desc')->select();
        foreach ($list as $key => $value) {
            $user = D('users')->where(array('user_id' => $value['user_id']))->field('nickname')->find();
            $list[$key]['nickname'] = $user['nickname'];
        }
        $show = $Page->show();
        $this->assign('level', $level);
        $this->assign('list', $list);
        $this->assign('page', $show);
        $this->display();
    }

    /**
     * 删除申请
     */
    public function delUserInfo() {
        $id = I('id');
        if (empty($id)) {
            $this->error('参数错误!');
        }
        D('UserInfo')->where(array('id' => $id))->delete();
        $this->success('成功删除!');
    }

    /**
     * 审核申请 
     */
    public function auditUserInfo() {
        $id = I('id');
        if (empty($id)) {
            $this->error('参数错误!');
        }

        $userinfo = D('UserInfo')->where(array('id' => $id))->find();
        $user = D('users')->where(array('user_id' => $userinfo['user_id']))->field('user_id,nickname,province,city,district')->find();
        $level = D('UserLevel')->where('level_id < 5')->getField('level_id,level_name,discount');
        $region = get_region_list();
        $userinfo['nickname'] = $user['nickname'];
        $userinfo['province_name'] = $region[$user['province']]['name'];
        $userinfo['city_name'] = $region[$user['city']]['name'];
        $userinfo['district_name'] = $region[$user['district']]['name'];

        if (IS_POST) {
            $data['status'] = I('post.status');
            D('UserInfo')->where(array('id' => $id))->save($data);
            if (I('post.status') == 1) {
                $user_data['is_distribut'] = 1;
                $user_data['discount'] = $level[$userinfo['apply_level']]['discount'] / 100;
                $user_data['level'] = $userinfo['apply_level'];
                D('users')->where(array('user_id' => $userinfo['user_id']))->save($user_data);
                D('UserInfo')->where(array('id' => $id))->setField('status', 1);
            }
            $this->success('操作成功!', U('Admin/User/userInfo'));
            exit();
        }
        $this->assign('user', $userinfo);
        $this->display();
    }

}
